package com.kb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kb.dao.DaoHelper;
import com.kb.common.ConnectionPool;


public abstract class DaoHelper<Type>  {
	private static final Log Log = LogFactory.getLog(DaoHelper.class);
	
	public int getTotalRecs(String sql) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ConnectionPool pool =new ConnectionPool();
			conn=pool.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				return rs.getInt(1);
			}
		} catch (Exception e) {
			Log.error(e.getLocalizedMessage());
		} finally {
			ConnectionPool.closeResultSet(rs);
			ConnectionPool.closePreparedStatement(ps);
			ConnectionPool.closeConnection(conn);
		}
		return 0;
	}

	public List<Type> getBySql(String sql) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			ConnectionPool pool =new ConnectionPool();
			conn=pool.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			List<Type> objs = new ArrayList<Type>();
			while (rs.next()) {
				objs.add(this.getRecFromResultSet(rs));
			}
			return objs;
		} catch (Exception e) {
			Log.error(e.getStackTrace());
		} finally {
			ConnectionPool.closeAll(rs, ps, conn);
		}
		return null;
	}
	
	public Type getById(long id, String sql) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ConnectionPool connPool =new ConnectionPool();
			conn = connPool.getConnection();
			ps = conn.prepareStatement(sql);
			
			ps.setLong(1, id);

			rs = ps.executeQuery();
			while (rs.next()) {
				return this.getRecFromResultSet(rs);
			}
		} catch (Exception e) {
			Log.error(e.getLocalizedMessage());
		} finally {
			ConnectionPool.closeAll(rs, ps, conn);
		}
		return null;
	}
	
	
	
	protected abstract Type getRecFromResultSet(ResultSet rs) throws SQLException;
	
	
	
}
